#include "mainwindow.h"
#include "cmdthread.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QPalette>
#include <stdio.h>
#include <QSharedMemory>
#include "xatom-helper.h"

using namespace std;

MainWindow::MainWindow(QString LaunchMode,QWidget *parent) : QWidget(parent)
{
    Launch_Mode =LaunchMode;
    m_move = false;
    flag = 1;
    setFocusPolicy(Qt::NoFocus);
    setAutoFillBackground(true);
    setFixedSize(550,320);

    titlewidget = new Title_bar(this);
    titlewidget->mini_btn->hide();
    titlewidget->move(0,0);

    tipwidget = new Tip_Widget(this);
    tipwidget->move(0,40);
    topwidget = new Top_Widget(this);
    topwidget->setFixedSize(550,36);
    topwidget->move(0,60);
    topwidget->hide();

    massagewidge = new Massage_Widget(this);
    massagewidge->move(0,96);
    massagewidge->hide();

    quitwidget = new Quit_Widget(false,0);
    MotifWmHints hints;
    hints.flags = MWM_HINTS_FUNCTIONS|MWM_HINTS_DECORATIONS;
    hints.functions = MWM_FUNC_ALL;
    hints.decorations = MWM_DECOR_BORDER;
    XAtomHelper::getInstance()->setWindowMotifHint(quitwidget->winId(), hints);
    quitwidget->move(0,0);
    quitwidget->hide();

    time0 = new QTimer();
    show_time = new QTimer();
    //创建线程
    this->ct = new CMDThread(Launch_Mode);
    determine_widget = new Quit_Widget(true,this);
    hints.flags = MWM_HINTS_FUNCTIONS|MWM_HINTS_DECORATIONS;
    hints.functions = MWM_FUNC_ALL;
    hints.decorations = MWM_DECOR_BORDER;
    XAtomHelper::getInstance()->setWindowMotifHint(determine_widget->winId(), hints);
    determine_widget->cancel_btn->hide();
    determine_widget->determine_btn->show();
    determine_widget->reduction_btn->hide();
    determine_widget->restart_btn->hide();
    determine_widget->hide();
    this->connect(this->determine_widget->close_btn,SIGNAL(clicked(bool)),this,SLOT(clicked_determinewidget_close_btn()));
    this->connect(this->determine_widget->determine_btn,SIGNAL(clicked(bool)),this,SLOT(clicked_determinewidget_close_btn()));
    //信号槽绑定
    this->connect(this->ct, SIGNAL(signal_messagebox()), this, SLOT(messagebox()));
    this->connect(this->ct, SIGNAL(signal_cmd_out(QString)), this, SLOT(on_cmd_out(QString)));
    this->connect(this->ct, SIGNAL(signal_is_complete(int)),this, SLOT(show_quit_widget(int)));
    this->connect(this->ct, SIGNAL(get_file_name(QString)),this,SLOT(slot_get_file_name(QString)));
    this->connect(this->ct, SIGNAL(signal_hide_mainwindow()),this, SLOT(hide_mainwindow()));
    connect(this->ct, &CMDThread::signal_lower_battery, this, &MainWindow::lower_battery);
    this->connect(this->titlewidget->close_btn,SIGNAL(clicked(bool)),this,SLOT(clicked_close_btn()));
    this->connect(this->tipwidget->upgrade_btn,SIGNAL(clicked(bool)),this,SLOT(clicked_upgrade_btn()));
    this->connect(this->tipwidget->backups_btn,SIGNAL(clicked(bool)),this,SLOT(clicked_backup_btn()));
    this->connect(this->titlewidget->mini_btn,SIGNAL(clicked(bool)),this,SLOT(clicked_mini_btn()));
    this->connect(this->time0,SIGNAL(timeout()),this,SLOT(slot_timeout()));
    this->connect(this->show_time,SIGNAL(timeout()),this,SLOT(show_click_upgrade()));
    this->connect(this->quitwidget->close_btn,SIGNAL(clicked(bool)),this,SLOT(clicked_close_btn()));
    this->connect(this->quitwidget->cancel_btn,SIGNAL(clicked(bool)),this,SLOT(clicked_close_btn()));
    this->connect(this->quitwidget->restart_btn,SIGNAL(clicked(bool)),this,SLOT(reboot()));
    this->connect(this->quitwidget->reduction_btn,SIGNAL(clicked(bool)),this,SLOT(clicked_reduction_btn()));
//   this->connect(this->ct, SIGNAL(signal_pb_startupdate_enabled()), this, SLOT(pb_startupdate_enabled()));
    if(LaunchMode == "MANUAL")
    {
//        show();
    }
    else
    {
        hide();
        this->ct->start();
    }

}

MainWindow::~MainWindow()
{
    delete this;
}

void MainWindow::lower_battery()
{
    QMessageBox msgBox;
    msgBox.setIcon(QMessageBox::Critical);
    msgBox.setText(tr("电量过低，请保持电量充足后升级"));
    QPushButton *btn = new QPushButton();
    btn->setText(tr("OK"));
    msgBox.addButton(btn, QMessageBox::AcceptRole);
    msgBox.exec();
    exit(0);
}

void MainWindow::rm_lockfile()
{
//    QString cmd = "rm "+QDir::homePath()+"/.cache/kylin-update-desktop.lock";
//    QString path = QDir::homePath()+"/.cache/kylin-update-desktop.lock";
//    QFile file;
//    if(file.exists(path))
//    {
//        char str[512] = {0};
//        qDebug() <<cmd;
//        qstrcpy(str,cmd.toStdString().c_str());
//        qDebug() << "str:" << str;
//        system(str);
//     }
}

//信息打印输出到界面
void MainWindow::on_cmd_out(QString line)
{
    this->massagewidge->massage_text->append(line);
    this->autoScroll();
}

void MainWindow::autoScroll()
{
    QTextCursor c = this->massagewidge->massage_text->textCursor();
    c.movePosition(QTextCursor::End);
    this->massagewidge->massage_text->setTextCursor(c);
}

//出错退出,当fail_reason=0时服务序列号匹配失败，为1是提权失败
void MainWindow::show_quit_widget(int fail_reason)
{
    this->ct->pingback("Fail");
    //this->ct->insert_imformation_to_db("Fail");
    copy_fileto_server("Fail");
    this->quitwidget->tip_label->setText(tr("update failed"));
//    this->quitwidget->tip_label->setStyleSheet("QLabel{color:#f4814c;font-size:24px}");
    this->quitwidget->cancel_btn->hide();
    this->quitwidget->restart_btn->hide();
    this->quitwidget->reduction_btn->hide();
    this->quitwidget->move(this->x()+(this->width()-this->quitwidget->width())/2,this->y()+(this->height()-this->quitwidget->height())/2);
    this->quitwidget->close_btn->show();
    if(fail_reason==0)
    {
        this->quitwidget->massge_label->setText(tr("The service serial number fails to match, it will exit after 5 seconds"));
    }
    else if(fail_reason==1)
    {
        this->quitwidget->massge_label->setText(tr("Failed to raise the right, will quit after 5 seconds"));
    }
    else
    {
        this->quitwidget->massge_label->setText(tr("Program exception, will exit in 5 seconds"));
    }
    if(this->Launch_Mode == "MANUAL")
    {
        this->quitwidget->show();
        this->flag = 0;
        this->time0->start(5000);
    }
    else
    {
        this->quitwidget->hide();
        this->hide();
        rm_lockfile();
        exit(0);
    }
}

void MainWindow::hide_mainwindow()
{
    this->hide();
}

//升级完成后提示
void MainWindow::messagebox()
{
    QProcess mproc;
    QFile file("/tmp/install-status");
    file.open(QIODevice::ReadOnly|QIODevice::Text);
    QTextStream out(&file);
    QString line = out.readLine();
    if(line == "0")
    {
        this->ct->pingback("Success");
        //this->ct->insert_imformation_to_db("Success");
        copy_fileto_server("Success");
        this->quitwidget->tip_label->setText(tr("update succeed"));
        this->quitwidget->massge_label->setText(tr("Restart is effective. Immediate restart is recommended"));
        this->quitwidget->reduction_btn->hide();
        this->quitwidget->move(this->x()+(this->width()-this->quitwidget->width())/2,this->y()+(this->height()-this->quitwidget->height())/2);
        if(this->Launch_Mode == "MANUAL")
        {
            this->quitwidget->show();
        }
        else
        {
            this->quitwidget->hide();
            this->hide();
            rm_lockfile();
            exit(0);
        }
    }
    else
    {
        this->ct->pingback("Fail");
        //this->ct->insert_imformation_to_db("Fail");
        copy_fileto_server("Fail");
        this->quitwidget->tip_label->setText(tr("update failed"));
//        this->quitwidget->tip_label->setStyleSheet("QLabel{color:#f4814c;font-size:24px}");
        this->quitwidget->massge_label->setText(tr("System may be abnormal, it is recommended to restore immediately"));
        this->quitwidget->restart_btn->hide();
        this->quitwidget->reduction_btn->show();
        this->quitwidget->close_btn->show();
        this->quitwidget->move(this->x()+(this->width()-this->quitwidget->width())/2,this->y()+(this->height()-this->quitwidget->height())/2);
        if(this->Launch_Mode == "MANUAL")
        {
            this->quitwidget->show();
        }
        else
        {
            this->quitwidget->hide();
            this->hide();
            rm_lockfile();
            exit(0);
        }
    }

}

//重启调用
void MainWindow::reboot()
{
    QString userName;
    QString command;
    command = "whoami";
    char buf[512] = {};
    FILE * read = popen("whoami","r");
    while((fgets(buf, sizeof(buf), read)) != NULL)
    {
        qDebug()<<buf;
    }
    userName = buf;
    userName.remove(QChar('\n'), Qt::CaseInsensitive);
    if(userName == "root")
    {
        system("reboot");
    }
    else
    {
        QDBusInterface *sessioniface;
        sessioniface = new QDBusInterface("org.gnome.SessionManager",
                                       "/org/gnome/SessionManager",
                                       "org.gnome.SessionManager",
                                       QDBusConnection::sessionBus());

        if (!sessioniface->isValid()){
            qDebug()<<qPrintable(QDBusConnection::sessionBus().lastError().message());
            exit(1);
        }
        QDBusReply<bool> reply = sessioniface->call("reboot");
        qDebug()<<"reboot:"<<reply.value();
    }

}

//void MainWindow::pb_startupdate_enabled()
//{
//    this->ui->pb_startupdate->setEnabled(true);
//}
/*
//升级过程中屏蔽关闭按钮
void MainWindow::closeEvent()
{
   if(CMDThread::qflag == 1){
           event->ignore();  //忽略退出信号，程序继续运行
   }
}
*/

//点击升级按钮
void MainWindow::clicked_upgrade_btn()
{
    show_time->start(5);
}

//点击立即还原按钮
void MainWindow::clicked_reduction_btn()
{
    //QProcess *process = new QProcess();
    system("/usr/bin/kybackup &");
    rm_lockfile();
    exit(0);
}

//点击升级显示窗口的动画
void MainWindow::show_click_upgrade()
{
    show_time->stop();
    char buf[50] = {};
    FILE * read = popen("uname -m","r");
    while((fgets(buf, sizeof(buf), read)) != NULL)
    {
    }
    QString machine = buf;
    machine = machine.simplified();
    if(machine == "mips64")
    {

        int width = this->width()+this->x()*2;
        int height = this->height()+this->y()*2;
        this->setFixedSize(550,630);
        this->move((width-this->width())/2,(height-this->height())/2);
        this->titlewidget->mini_btn->show();
        this->tipwidget->hide();
        this->topwidget->show();
        this->massagewidge->show();
        CMDThread::qflag = 1;
        this->ct->start();
    }
    else
    {
        int width = this->width()+this->x()*2;
        int height = this->height()+this->y()*2;
        if(this->height()<=630)
        {
            this->setFixedHeight(this->height()+5);
            this->move((width-this->width())/2,(height-this->height())/2);
            if(this->tipwidget->height()-1>=0 && this->tipwidget->width()-2>=0)
            {
                this->tipwidget->setFixedSize(this->tipwidget->width()-2,this->tipwidget->height()-1);
                this->tipwidget->move(this->x()+(this->width()-this->tipwidget->width())/2,this->y()+(this->height()-this->tipwidget->height())/2);
                this->tipwidget->show();
            }
            if(this->tipwidget->height()==0)
            {
                this->tipwidget->hide();
            }
            show_time->start(10);
        }
        if(this->height()==630)
        {
            this->setFixedSize(550,630);
            this->move((width-this->width())/2,(height-this->height())/2);
            this->titlewidget->mini_btn->show();
            this->tipwidget->hide();
            this->topwidget->show();
            this->massagewidge->show();
            CMDThread::qflag = 1;
            this->ct->start();
        }
    }
}

//点击关闭按钮
void MainWindow::clicked_close_btn()
{
    qDebug() << "exit";
    if(CMDThread::qflag == 0)
    {
        qDebug() << "rm";
//        rm_lockfile();
        exit(0);
    }
}

//关闭提示框
void MainWindow::clicked_determinewidget_close_btn()
{
    this->determine_widget->hide();
}

//点击最小化按钮
void MainWindow::clicked_mini_btn()
{
    this->showMinimized();
}

//点击提示界面的备份按钮
void MainWindow::clicked_backup_btn()
{
    QFile file;
    if(file.exists("/etc/.bootinfo"))
    {
        ifstream in;
        in.open("/etc/.bootinfo",ios::in);
        char read_buf[512] = {};
        QString readline ="";
        while(in.getline(read_buf,sizeof(read_buf)))
        {
            readline = read_buf;
            if(readline.contains("RECOVERY_DEV_UUID="))
            {
                int n = readline.indexOf("=");
                int len = strlen(read_buf);
                if(readline.mid(n+1,len) != "")
                {
                    system("/usr/bin/kybackup &");
                }

            }
        }
    }
    else
    {
        this->determine_widget->tip_label->setText(tr("No partitions available"));
        this->determine_widget->move(this->x()+(this->width()-this->quitwidget->width())/2,this->y()+(this->height()-this->quitwidget->height())/2);
        determine_widget->show();
    }
}

//定时器超时
void MainWindow::slot_timeout()
{
    rm_lockfile();
    exit(0);
}

//实现鼠标移动窗口
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        //移动中的鼠标位置相对于初始位置的相对位置.
        QPoint relativePos = event->globalPos() - this->m_startPoint;
        //然后移动窗体即可.
        this->move(this->m_windowPoint + relativePos );
    }

}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    //当鼠标左键点击时.
    if (event->button() == Qt::LeftButton)
    {
        this->m_move = true;
        this->m_startPoint = event->globalPos();
        this->m_windowPoint = this->frameGeometry().topLeft();
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
       {
           //改变移动状态.
           this->m_move = false;
       }
}

void MainWindow::copy_fileto_server(QString status)
{
    QString file_name = QDir::homePath()+"/.cache/kylin-update-desktop.log";
    QFile file(file_name);
    file.open(QIODevice::ReadOnly);
    int file_len = file.size();
    QDataStream in(&file);
    char *m_buf = new char[file_len];
    in.readRawData( m_buf, file_len);
    file.close();
    QNetworkAccessManager *_uploadManager = new QNetworkAccessManager;
    QNetworkReply *_reply;
    QString Url2 = "http://archive.kylinos-intranet.cn/kylin-update-manager-server/get_file.php?";
    Url2 = Url2+send_filename;
    QUrl tr(Url2);
    qDebug()<<Url2;
    QNetworkRequest request;
    request.setUrl(tr);
    QByteArray arr = QByteArray(m_buf, file_len);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/form-data");
    //request.setHeader(QNetworkRequest::ContentLengthHeader, arr.length());
    FILE * check_machine = popen("uname -m","r");
    char buff[512] = {0};
    QString machine = "";
    while((fgets(buff, sizeof(buff), check_machine)) != NULL)
    {
        machine = QString(buff);
    }
    machine = machine.replace("\n","");
    qDebug()<<machine;
    if(machine !="mips64")
    {
        _reply = _uploadManager->post(request,arr);
    }
    qDebug()<<_reply;
    qDebug()<<status;
    qDebug()<<"over";
}

void MainWindow::slot_get_file_name(QString file_name)
{
    send_filename = file_name;
}

